package org.ice4apps.talk.redirectCallHandler;

import java.io.IOException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.sip.SipServlet;
import javax.servlet.sip.SipServletContextEvent;
import javax.servlet.sip.SipServletListener;
import javax.servlet.sip.SipServletRequest;
import javax.servlet.sip.SipServletResponse;
import org.ice4apps.talk.entity.User;

/* This is the serlvet handle the redirection of the call
 * Any call come to his serverlet will be routed to the final destination
 * by dipping into the DB  
 */

public class RedirectServlet extends SipServlet implements SipServletListener {
  public void init(ServletConfig config) throws ServletException {
    super.init(config);
  }    

  public void doInvite(SipServletRequest request) {
    String requestUri = request.getRequestURI().toString();

    if (requestUri.contains("ice-term"))
    {
      // This is designated to the local server for the Termination Porcessing
      //TalkUtil talkUtil = TalkUtil.instance();
      //String userAlias = talkUtil.getUser(request.getRequest().getURI());
      //User fromUser = talkUtil.getUser(userAlias);

      //TODO : Remove after testing
      String userAlias = "ice-term-3061974010";
      User fromUser = new User();
      fromUser.setUserName("3061974012");

      //TODO : Get the serving Server from the DB
      String newContact = userAlias + "@127.0.0.1:5060";
      int responseCode = SipServletResponse.SC_MOVED_TEMPORARILY;
      SipServletResponse resp = request.createResponse(responseCode);
      resp.addHeader("Contact", newContact);
      try
      {
        resp.send();
      } 
      catch (IOException e)
      {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
  }

  @Override
  public void servletInitialized(SipServletContextEvent arg0)
  {
    // TODO Auto-generated method stub
    
  }
}